package contrl

import (
	"core/rds"
	"core/utils"
	"db"
	"strconv"

	"github.com/gin-gonic/gin"
)

type RankContrl struct{}

type (
	RankPlayer struct {
		BasicPlayer
		Rank  int
		Score int64
	}
)

func loadRankWithUsers(rankKey string, limit int64) (rankList []RankPlayer, err error) {
	list, err := rds.GetDefaultClient().LoadRankList(rankKey, 0, limit)
	if err != nil {
		return
	}
	ids := make([]int64, len(list))
	for k, rank := range list {
		ids[k] = utils.ToInt64(rank.Member)
	}
	users := db.LoadByIds(ids)
	rankList = make([]RankPlayer, len(list))
	for k, rank := range list {
		player, found := users[utils.ToInt64(rank.Member)]
		if !found {
			continue
		}
		rankList[k] = RankPlayer{
			BasicPlayer: genBasicPlayer(player),
			Rank:        rank.Rank,
			Score:       rank.Score,
		}
	}
	return
}

type RankListResponse struct {
	List   []RankPlayer
	MyRank int64
}

func (*RankContrl) List(c *gin.Context) (res interface{}, e Error) {
	sign := GetSign(c)
	rankKey := db.MakeWaterRankKey(sign.Uid)
	rankList, err := loadRankWithUsers(rankKey, 100)
	if err != nil {
		return nil, GenError(err)
	}
	myRank, err := rds.GetDefaultClient().LoadMyRank(rankKey, strconv.FormatInt(sign.Uid, 10))
	if err != nil {
		utils.Error(err)
	}
	res = RankListResponse{
		List:   rankList,
		MyRank: myRank,
	}
	return
}
